import React from 'react'
import T from '../../lib/T'
import api from '../../api'
import { actions, connect } from 'mirrorx'
import { Checkbox, Modal, Pagination } from 'antd'
import IconDom from '../../component/IconDom'
import Preview from '../product/preview'
// 每个Item底部按钮组
import BottomBtns from './Buttons'

const CheckboxGroup = Checkbox.Group

class Promotion extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      currentPage: 1,
      pageSize: 8,
      rowTotal: 0,
      filterList: [
        { filterName: 'Status', id: 0 },
        { filterName: 'Insurance Company', id: 2 },
        { filterName: 'Category', id: 1 }
      ],
      activeItem: 0,
      activeListItem: '',
      filterData: {},
      productList: [],
      insuCheckedList: [],
      cateCheckedList: [],
      statusCheckedList: [],
      statusList: [],
      insurerIdList: [],
      categoryCodeList: [],
      tipsModal: false,
      visible: false,
      promotionData: null,
      viewTips: '',
      channelGoodsId: '',
      operationDesc: '', // 点击的操作 delete或disable
      tipText: '', // 操作确认提示框的文案
      expiredTips: ''
    }
    this.tabFilter = this.tabFilter.bind(this)
    // 选择状态
    this.changeStatus = this.changeStatus.bind(this)
    // 选择保险公司
    this.changeInsurerList = this.changeInsurerList.bind(this)
    // 选择产品分类
    this.changeCateList = this.changeCateList.bind(this)
    // 获取渠道商品列表
    this.queryChannelGoodsPage = this.queryChannelGoodsPage.bind(this)
    // 翻页操作
    this.changePage = this.changePage.bind(this)
    // 确认框确定按钮的操作
    this.operate = this.operate.bind(this)
    // 打开详情
    this.toView = this.toView.bind(this)
    // 打开操作确认框
    this.showTips = this.showTips.bind(this)
  }
  componentDidMount () {
    T.ajax({
      url: 'api/uc/user/getChannelInfo'
    }).then((res) => {
      if (res.code === 0) {
        let { partnerId: channelCompanyId } = res.data
        this.setState({ channelCompanyId }, () => {
          this.queryChannelGoodsPage()
          this.queryChannelGoodsSearchCondition()
        })
      }
    })
  }
  queryChannelGoods (channelGoodsId) {
    T.ajax({
      url: api.queryChannelGoods.path,
      data: {
        channelGoodsId
      }
    }).then((res) => {
      if (res.code === 0) {
        this.setState({
          promotionData: res.data
        })
      }
    })
  }
  getSrc (code) {
    // 获取图片路径
    let src = `/ajax/proxy/api/goods/file/downloadFile?fileUniqueCode=${code}`
    return src
  }
  // channelCompanyId: '',statusCheckedList: '',insurerIdList: ''
  queryChannelGoodsPage () {
    let { currentPage, pageSize, channelCompanyId, statusList, categoryCodeList, insurerIdList } = this.state
    let condition = {
      channelCompanyId
    }
    insurerIdList.length > 0 && (condition.insurerIdList = insurerIdList)
    statusList.length > 0 && (condition.statusList = statusList)
    categoryCodeList.length > 0 && (condition.categoryCodeList = categoryCodeList)
    T.ajax({
      url: api.queryChannelGoodsPage.path,
      loading: true,
      data: {
        condition,
        pageIndex: currentPage,
        pageSize
      }
    }).then((res) => {
      if (res.code === 0) {
        let { rows: productList, rowTotal } = res.data
        // 给每个Item加上图片路径的Key
        productList = productList.map(item => {
          let src = this.getSrc(item.smallImage)
          item.src = src
          return item
        })
        this.setState({
          productList,
          rowTotal
        })
      }
    })
  }

  tabFilter (activeItem) {
    // 筛选里面的Tab
    this.setState({ activeItem })
  }
  changeInsurerList (insuCheckedList) {
    let insurerIdList = insuCheckedList.map(item => {
      item = item.replace(/insure/g, '')
      return Number(item)
    })
    this.setState({
      insuCheckedList,
      insurerIdList
    }, () => {
      this.queryChannelGoodsPage()
    })
  }
  changeCateList (cateCheckedList) {
    let categoryCodeList = cateCheckedList.map(item => {
      item = item.replace(/cate/g, '')
      return Number(item)
    })
    this.setState({
      cateCheckedList,
      categoryCodeList
    }, () => {
      this.queryChannelGoodsPage()
    })
  }
  changeStatus (statusCheckedList) {
    let statusList = statusCheckedList.map(item => {
      item = item.replace(/status/g, '')
      return Number(item)
    })
    this.setState({
      statusCheckedList,
      statusList
    }, () => {
      this.queryChannelGoodsPage()
    })
  }
  queryChannelGoodsSearchCondition () {
    let { channelCompanyId } = this.state
    channelCompanyId && T.ajax({
      url: api.queryChannelGoodsSearchCondition.path,
      loading: true,
      data: { channelCompanyId }
    }).then((res) => {
      if (res.success && res.data) {
        let { agreementGoodsCategoryList: categoryList, agreementGoodsInsurerList: insurerList } = res.data

        categoryList = categoryList.map((item) => {
          item.label = item.categoryName
          item.value = 'cate' + item.categoryCode // 因为后台返回id会相同，加前缀防止id区分
          return item
        })
        insurerList = insurerList.map((item) => {
          item.label = item.insurerName
          item.value = 'insure' + item.insurerId
          return item
        })
        let filterData = {}

        filterData.categoryList = categoryList
        filterData.insurerList = insurerList
        // 加上status是为了避免id重复
        filterData.statusList = [
          { label: 'Draft', value: 'status1' },
          { label: 'Ready', value: 'status2' },
          { label: 'Online', value: 'status3' },
          { label: 'Offline', value: 'status4' },
          { label: 'Expired', value: 'status5' }
        ]
        this.setState({
          filterData
        })
      }
    })
  }
  changePage (currentPage) {
    this.setState({ currentPage }, () => {
      this.queryChannelGoodsPage()
    })
  }
  update (channelGoodsId, status) {
    T.ajax({
      url: api.updateChannelGoods.path,
      loading: true,
      data: {
        channelGoodsId,
        operation: status
      }
    }).then(res => {
      this.setState({ tipsModal: false })
      this.queryChannelGoodsPage()
    })
  }
  showTips (item, str) {
    this.setState({
      tipsModal: true,
      operationDesc: str,
      channelGoodsId: item.id
    })
    if (str === 'delete') {
      let text = item.status === 1 ? 'Draft' : 'Goods'
      this.setState({
        tipText: `Do you want to  delete this ${text} ?`
      })
    } else if (str === 'disable') {
      this.setState({
        tipText: 'Do you want to disable this online goods?'
      })
    }
  }
  operate (item) {
    let { operationDesc, channelGoodsId } = this.state
    if (operationDesc === 'delete') {
      this.update(channelGoodsId, 1)
    } else if (operationDesc === 'disable') { // online
      this.update(channelGoodsId, 2)
    }
  }
  toView (channelGoodsId, status) {
    /*
      1-Draft（草稿），
      2-Ready（暂存），
      3-Online（上线），
      4-Offline（下线），
      5-Expired（过期）
    */
    let expiredTips = ''
    if (status === 4) {
      expiredTips = 'This insurance goods is offline. You need to republish it if you want to promote again.'
    } else if (status === 5) {
      expiredTips = '(Your agreement contract is expired, please contact insurer and admin to renewal your agreement.)'
    }
    this.setState({
      viewTips: '',
      expiredTips,
      visible: true
    }, () => {
      this.queryChannelGoods(channelGoodsId)
    })
  }
  render () {
    let { filterList, promotionData, tipText, visible, currentPage, activeListItem, tipsModal, pageSize, activeItem, filterData, productList, rowTotal } = this.state
    let { partnerId: channelCompanyId = '' } = this.props.mainModel.userInfo

    let { menuModel } = this.props
    let menuAuth = false
    if (menuModel && menuModel.grantedMenus) {
      console.log('grantedMenus', menuModel.grantedMenus)
      menuAuth = T.getMenuAuth('Promotion', menuModel.grantedMenus)
    }

    console.log('menuAuth', menuAuth)
    return <div>
      <div className='promotion'>
        <div className='filter-box'>
          <div className='filter-tab'>
            <span className='filter-title'>Filter:</span>
            {
              filterList.map(item => {
                return <span
                  onClick={() => this.tabFilter(item.id)}
                  className={activeItem === item.id
                    ? 'filter-item active-item'
                    : 'filter-item'}
                  key={item.id}>
                  {item.filterName}
                  <IconDom
                    className='icon-arrow'
                    code='icon-arrow' />
                </span>
              })
            }
          </div>
          <div className='filter-content'>
            {
              activeItem === 1
                ? <CheckboxGroup
                  options={filterData.categoryList}
                  value={this.state.cateCheckedList}
                  onChange={this.changeCateList} />
                : activeItem === 2
                  ? <CheckboxGroup
                    options={filterData.insurerList}
                    value={this.state.insuCheckedList}
                    onChange={this.changeInsurerList} />
                  : <CheckboxGroup
                    options={filterData.statusList}
                    value={this.state.statusCheckedList}
                    onChange={this.changeStatus} />
            }

          </div>
        </div>
        <div className='pro-list'>
          {
            productList.map((item, index) => {
              let statusClassName = 'status-desc '
              let status = Number(item.status)
              status === 2 && (statusClassName += 'ready-bg')
              status === 3 && (statusClassName += 'online-bg')
              status === 4 && (statusClassName += 'offline-bg')
              status === 5 && (statusClassName += 'expired-bg')
              return <div
                onClick={() => {
                  this.setState({ activeListItem: item.id })
                }}
                key={index}
                className={activeListItem === item.id
                  ? 'list-item  active-list-item'
                  : 'list-item'}>
                <span
                  className={statusClassName}>{item.statusName}</span>
                {
                  item.smallImage
                    ? <img
                      className='product-img'
                      src={item.src} />
                    : <div className='no-image'>
                      <IconDom code='icon-no-image' />
                    </div>

                }
                <div className='t-ellipsis product-name'>{item.name}</div>
                <div className='introduction'>
                  {item.introduction}
                </div>
                <div className='date'>
                  {item.startDateStr && item.startDateStr.replace(/-/g, '/')} - {item.startDateStr && item.endDateStr.replace(/-/g, '/')}
                </div>

                {/* start 每个Item底部按钮组 */}
                <BottomBtns
                  menuAuth={menuAuth}
                  toView={this.toView}
                  showTips={this.showTips}
                  item={item}
                  channelCompanyId={channelCompanyId}
                />
                {/* end 每个Item底部按钮组 */}

              </div>
            })
          }
          {
            productList.length === 0
              ? <div className='no-data'>
                <div className='no-data-icon'>
                  <IconDom code='icon-zanwuneirong' />
                </div>
              No Data
              </div> : ''
          }
        </div>
        {
          productList.length > 0
            ? <div className='page'>
              <Pagination
                showQuickJumper
                total={rowTotal}
                current={currentPage}
                pageSize={pageSize}
                onChange={this.changePage} />
            </div>
            : ''
        }

      </div>
      {
        visible ? <Preview
          promotionData={promotionData}
          viewTips={this.state.expiredTips}
          cancelVisible={() => this.setState({ visible: false })}
          visible={this.state.visible} />
          : ''
      }
      <Modal
        title='Tips'
        okText='yes'
        cancelText='No'
        visible={tipsModal}
        onOk={this.operate}
        onCancel={() => this.setState({ tipsModal: false })}
      >
        <p>{tipText}</p>
      </Modal>
    </div>
  }
}

export default connect(state => {
  return state
})(Promotion)
